<?php
/*
 * index 控制器
 */

class Index_Action{

	private $site_title = '方程式客资管理系统';
    private $options_cache;

	function __construct(){
		global $CACHE;
        $this -> options_cache = $CACHE -> readCache('options');
	}

	function index(){
		$this -> login();
	}

	function login(){
        
		if(ISLOGIN === true){
            idooDirect(APP_URL.'manage/index');
        }

		$page_title = '用户登录';
		$site_title = $page_title . ' - ' .$this->site_title;

		include View::getView('login');
	}

	function logout(){
		setcookie(AUTH_COOKIE_NAME, ' ', time() - 31536000, '/');
    	idooDirect(APP_URL.'index/index');
	}

	function handle(){
		$action = isset($_POST['action'])?trim($_POST['action']):'';
		$methodName = 'handle_'.$action;
		if(method_exists($this, $methodName)){
			$this -> $methodName();
		}
	}

	function handle_login(){
		$username = isset($_POST['username']) ? addslashes(trim($_POST['username'])) : '';
        $password = isset($_POST['password']) ? addslashes(trim($_POST['password'])) : '';
        $ispersis = true;
        $img_code = isset($_POST['imgcode']) ? addslashes(trim(strtoupper($_POST['imgcode']))) : '';
        $safecode = isset($_POST['safecode']) ? addslashes(trim($_POST['safecode'])) : '';
        $isAjax = isset($_POST['isAjax'])?intval($_POST['isAjax']):0;

        session_start();
        if($img_code != $_SESSION['code']){
            echo '{"result":911,"msg":"验证码错误！"}';
            exit;
        }

        $options_cache = $this -> options_cache;
        if($safecode != $options_cache['safecode']){
        	exit('{"result":911,"msg":"安全码不正确！"}');
        }

        $User_Model = new User_Model();
        $loginAuthRet = LoginAuth::checkUser($username, $password, $img_code);
        
        if ($loginAuthRet === true) {
            LoginAuth::setAuthCookie($username, $ispersis);
            echo '{"result":200,"msg":"登录成功！"}';
        } else{
            //LoginAuth::loginPage($loginAuthRet);
            echo '{"result":102,"msg":"登录失败！'.$loginAuthRet.'"}';
        }
	}

}